//
//  VIZOAuthVC.swift
//  VIZ微博
//
//  Created by 位立志 on 16/4/9.
//  Copyright © 2016年 位立志. All rights reserved.
//

//授权回调页：http://baidu.com
//取消授权回调页：http://http://www.jianshu.com
//App Key：4274556324
//App Secret：0051c737192f61155911a503c76f180f


import UIKit
import SVProgressHUD

//private let userInfoKey = "userInfoKey"

class VIZOAuthVC: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
    
        //设置webView代理
        webView.delegate = self
    
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id="+client_id+"&redirect_uri="+redirect_uri
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        //加载webView
        webView.loadRequest(request)

        //设置导航条
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "fullAcount")

        
    }

    //关闭事件
    @objc private func close () {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //自动填充
    @objc private func fullAcount() {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18330236306', document.getElementById('passwd').value = 'weilizhi606323'")
        
    }
}


extension VIZOAuthVC : UIWebViewDelegate {
    
    //开始加载的时候
    func webViewDidStartLoad(webView: UIWebView) {
        //开启等待显示器
        SVProgressHUD.show()
    }
    
    //加载完毕的时候
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭等待显示器
        SVProgressHUD.dismiss()
        
        //设置头
        self.title = webView.stringByEvaluatingJavaScriptFromString("document.title")
        
    }
    
    //协议方法返回值为 bool类型 如果返回 true 就可才正常工作,否则就不能够工作
    //MARK:在授权成功的回调页中获取 授权code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取url的字符串格式
        let urlString = request.URL?.absoluteString ?? ""
        //print(urlString)
        //获取code   d36a5af9361c79d154727805bd411dc9
        let flagStr = "code="
        if urlString.containsString(flagStr) != false {
            
            let range = urlString.rangeOfString(flagStr)
            
            let code = urlString.substringFromIndex((range?.endIndex)!)
            
            //print("code = "+code)
            //使用授权码获取accesstoken
            
            //let UserViewAccountModel = VIZUserViewAccountModel
            let userViewAccountModel = VIZUserViewAccountModel.shardInstance
            userViewAccountModel.getAccessTocken(code, finished: { (isSuccess) -> () in
                //登录失败
                if isSuccess == false{
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }else{
                    SVProgressHUD.showSuccessWithStatus("登录成功")
                    //登录成功后需要将页面释放
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(VIZchange, object: nil)
                    })
                }
            })
            //不加载授权成功的回调页面
            return false
            
        }
        
       return true
    }
    
}













